package com.itany.shop.service.impl;

import com.itany.shop.dao.ItemDao;
import com.itany.shop.dao.OrderDao;
import com.itany.shop.dao.ProductDao;
import com.itany.shop.entity.Item;
import com.itany.shop.entity.Order;
import com.itany.shop.entity.User;
import com.itany.shop.exception.UserNotLoginException;
import com.itany.shop.factory.ObjectFactory;
import com.itany.shop.service.OrderService;
import com.itany.shop.util.ParamterUtil;
import com.itany.shop.vo.Cart;

import java.util.List;

/**
 * @author MissChen
 * @version 1.0
 * @date 2023 年12月22日 14:58
 */
public class OrderServiceImpl implements OrderService {
    private OrderDao orderDao = (OrderDao) ObjectFactory.getObject("orderDao");
    private ItemDao itemDao = (ItemDao) ObjectFactory.getObject("itemDao");
    @Override
    public String createOrder(Cart cart, User user) throws UserNotLoginException {
        if (cart == null || user == null) {
            throw new UserNotLoginException("请先登录");
        }
        Order order = new Order();
        order.setNo(ParamterUtil.createNo());
        order.setPrice(cart.getPrice());
        order.setUser(user);

        //插入订单并返回主键
        Integer id = orderDao.insertReturnPrimaryKey(order);
        order.setId(id);

        //插入明细
        List<Item> items=cart.getItems();
        for(Item item:items){
            item.setOrder(order);
            itemDao.insertItem(item);
        }

        return order.getNo();
    }
}
